# -*- coding: utf-8 -*-
# author: Ryan
# time: 2022/4/6
from itsdangerous import TimedJSONWebSignatureSerializer, SignatureExpired, BadSignature
from flask import Flask, send_file, request, send_from_directory, g
from flask_cors import *  # 导入模块
from passlib.hash import sha256_crypt
from flask_httpauth import HTTPTokenAuth
# from send_email import send_email
from flask_sqlalchemy import SQLAlchemy
from flask import Flask, request, jsonify
auth = HTTPTokenAuth(scheme='JWT')
app = Flask(__name__)

CORS(app, resources={r"/*": {"origins": "*"}}, supports_credentials=True)  # 设置跨域
# 创建数据库sqlalchemy工具对象

# class Config():
#     """配置参数"""
#     # 设置连接数据库的URL
#     user = 'root'
#     password = 'asd007881'
#     database = 'laat'
#     app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://%s:%s@localhost:3306/%s' % (user, password, database)
#     app.config['SECRET_KEY'] = "asd007881"
#     # 设置sqlalchemy自动更跟踪数据库
#     SQLALCHEMY_TRACK_MODIFICATIONS = True
#
#     # 查询时会显示原始SQL语句
#     # app.config['SQLALCHEMY_ECHO'] = True
#     app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
#     app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
#     # 禁止自动提交数据处理
#     app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = False
#
#
# app.config.from_object(Config)
# db = SQLAlchemy(app)
s=TimedJSONWebSignatureSerializer('beta_website_token',expires_in=72000)



@auth.verify_token
def verify_token(token):
    g.user = None
    s = TimedJSONWebSignatureSerializer('token')
    try:
        data = s.loads(token)
    except SignatureExpired:
        # token正确但是过期了
        return jsonify({'message':'用户登录过期'})
    except BadSignature:
        # token错误
        return jsonify({'message':'token错误'})
    if 'idUser' in data:
        # db = get_db()
        # g.user = db.execute(
        #     'SELECT * FROM User WHERE idUser = ?', (data['idUser'],)
        # ).fetchone()
        return jsonify({ 'code':200, 'message':'Login success' })
    return False
@auth.error_handler
def error_handler():
    return jsonify({ 'code':401, 'message':'401 Unauthorized Access' })


@app.route('/index')
# @auth.login_required
def index():
    return "hello"

@app.route('/get_token',methods=['POST'])
# @auth.login_required
def get_token():
    req = request.json
    username = str(req['username'])
    password = str(req['password'])
    token = s.dumps({'username': username, 'password': password}).decode('utf-8')
    return jsonify({'code':200,'message':'登录成功','token':token })


@app.route('/login', methods=['GET'])
@auth.login_required
def login():
    return jsonify({'code':200,'message':'登录成功' })

@app.route('/user_info', methods=['POST'])
@auth.login_required
def get_user_info():
    req=request.json
    username=str(req['username'])
    return jsonify({'message':'用户名是'+username })

if __name__ == '__main__':
    app.run(debug=True,host='192.168.50.46',port=3399)